#适用UTF-8格式的文本文档
#使用其它格式的文本文档
#iv=open('E:\\python learning notes\\files UTF-16 BE.txt','r')
#print(iv.read())#UnicodeDecodeError: 'gbk' codec can't decode byte 0xfe in position 0: illegal multibyte sequence
'''
iv=open('E:\\python learning notes\\files UTF-16 BE.txt','r',encoding='utf-16 be')
print(iv.read())#hello world
#二进制读取
iv=open('E:\\python learning notes\\files.txt','rb')
filetext=iv.read()
print(filetext)#b'hello world'
#注：如果前面发生了异常，那么后面就无法正常关闭
#可以使用try语法
iv=open('E:\\python learning notes\\files UTF-16 BE.txt','w+',encoding='utf-16 be')
try:
    iv.write('你好')
finally:
    iv.close()
#可以保障文件正常关闭
#也可以使用with
with open('E:\\python learning notes\\files UTF-16 BE.txt','a',encoding='utf-16 be') as iv:
    iv.write('好')
print(iv.closed)#True
iv=open('E:\\python learning notes\\files.txt','r')
filetext=iv.read(5)
filetext2=iv.read(5)
print(filetext)#hello
print(filetext2)# worl
position=iv.tell()
print(position)#10,即光标所指的位置
position=iv.seek(0,0)#将光标重新指向开始
filetext2=iv.read(5)
print(filetext2)#hello
'''
#综上
#文件备份
#思路：先读后写
'''
iv=open('E:\\python learning notes\\files.txt','r')
file_content=iv.read()
v=open('E:\\python learning notes\\files(2).txt','w')
v.write(file_content)
#可以看到对应地址下出现了这个文件
'''
#writelines可以写入多行文本
#v=open('E:\\python learning notes\\files(1).txt','w')
#v.writelines(['This is the first line.\n','This is the second line.\n'])
#readline可以读取一行
#用下面的代码将多行文本转化成一行
v=open('E:\\python learning notes\\files(1).txt','r')
file_text=v.readline()
index=file_text.rfind('\\')
while file_text:
    print(file_text[:index],end=' ')
    file_text=v.readline()
    index = file_text.rfind('\\')
print('\n')
v.seek(0,0)
#readlines读多行
print(v.readlines())

